import { ConfigureService } from '@app/configure';
import { JwtVerifyService } from '@app/jwt-verify';
import { CanActivate, ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { ReqAttrs } from '../../constant';
import { USER_SOURCE } from 'constant/USER_SOURCE';

@Injectable()
export class AuthGuard implements CanActivate {
	@Inject()
	private readonly config:ConfigureService
	@Inject()
	private readonly jwt:JwtVerifyService


	async canActivate(
		context: ExecutionContext,
	): Promise<boolean> {



		console.log('--------------')


		let request = context.switchToHttp().getRequest()

		const route = request.route
		let path:string = route.path
		const whites = this.config.get<string[]>('whites')

		const routePrefix = this.config.get('API_PRE_FIX')
		if(routePrefix != undefined && routePrefix.length > 0) {
			path = path.substring(routePrefix.length + 1)
		}



		const isWhite = whites.includes(path)

		//request[ReqAttrs.USER_ID] = 1001030//payload.key
		//request[ReqAttrs.SCHOOL_ID] = 1001030


		const token = request.headers.authorization
		//request[ReqAttrs.USER_ID] = 1001030
		
		if(token) {
			const payload = this.jwt.verify(token)

			//console.log(payload)

			//console.log(payload)


			if(payload) {
				request[ReqAttrs.USER_ID] = payload.key
			}

			// if(!payload && !isWhite) return false

			
			// request[ReqAttrs.USER_ID] = payload.key
			//request[ReqAttrs.SCHOOL_ID] = payload.key
			
		}

		// if(request.headers['client-type']) {
		// 	request[ReqAttrs.IS_WX] = request.headers['client-type'] == 'wx'
		// 	request[ReqAttrs.IS_ALI] = request.headers['client-type'] == 'ali'
		// 	request[ReqAttrs.CLIENT_SOURCE] = request[ReqAttrs.IS_WX] ? USER_SOURCE.WX : USER_SOURCE.ALI
		// }

		return true;
	}
}
